//
//  AEImagePlayerView.m
//  AETravel
//
//  Created by carshoel on 16/4/22.
//  Copyright © 2016年 carshoel. All rights reserved.
//

#import "AEImagePlayerView.h"
#import "UIImageView+WebCache.h"

typedef enum {
    AEImagePlayerViewMoveDirectionWait,//等待状态
    AEImagePlayerViewMoveDirectionRight,//向右滑动
    AEImagePlayerViewMoveDirectionLeft,//向左滑动
} AEImagePlayerViewMoveDirection;


@interface AEImagePlayerView ()

/**
 *  本地图片
 */
@property (nonatomic, strong)NSMutableArray *downloadImages;

/**
 *  当前显示的imageView
 */
@property (nonatomic, weak)UIImageView *currentImageView;

/**
 *  等待显示的imageView
 */
@property (nonatomic, weak)UIImageView *willAppearImageView;


/**
 *  定时器
 */
@property (nonatomic, strong)NSTimer *timer;


/**
 *  解决同一个uiview 的画面掉用两次
 */
@property (nonatomic, assign,getter=isOnesAnimate)BOOL onesAnimate;//解决同一个uiview动画掉用两次

/**
 *  显示的数据的角标标
 */
@property (nonatomic, assign)long long index;


/**
 *  用户手指滑动的方向
 */
@property (nonatomic, assign)AEImagePlayerViewMoveDirection  moveDirection;//用户移动方向

@end


@implementation AEImagePlayerView


/**
 *  设置滑动方向
 */
- (void)setMoveDirection:(AEImagePlayerViewMoveDirection)moveDirection{
   
//    if (_moveDirection == moveDirection)return;//同一次滑动中方向相同,直接返回
//    _moveDirection = moveDirection;
//    if (self.moveDirection == AEImagePlayerViewMoveDirectionWait)return;// 滑动结束,赋值等待状态,直接返回.
//    
//    CGFloat x ;
//    if (self.moveDirection == AEImagePlayerViewMoveDirectionRight) {// 向右滑动
//        x = 0;
//        self.index ++;
//        NSLog(@"right");
//    }else if(self.moveDirection == AEImagePlayerViewMoveDirectionLeft){//向左滑动
//        x = self.frame.size.width * 2;
//        self.index --;
//        NSLog(@"left");
//    }
//    
//    //设置将要显示的是图的位置 (根据滑动的方向)
//    self.willAppearImageView.frame = CGRectMake(x, 0, self.frame.size.width, self.frame.size.height);
}

/**
 *  设置角标,同时自动设置相应要显示的图片
 */
- (void)setIndex:(long long)index{
    
//    //如本地图片数组里没有图片 或者 要赋值的角标和当前的角标一样 直接返回
//    if (_index == index || !self.downloadImages.count)return;
//
//    //设置角标越界问题
//    if (index > self.downloadImages.count -1)index = 0;
//    if (index < 0)index = self.downloadImages.count - 1;
//    
//    //赋值角标
//    _index = index;
//
//    //设置显示的图片
//    self.willAppearImageView.image = self.downloadImages[_index];
}


/**
 *  懒加载本地图片数据
 */
- (NSMutableArray *)downloadImages{
    if(!_downloadImages){
        _downloadImages = [NSMutableArray array];
    }
    return _downloadImages;
}

/**
 *  通过类方 创建一个图片播放器
 */
+ (instancetype)playerViewWithImages:(NSArray *)images{
    AEImagePlayerView *ipv = [[self alloc] init];
    ipv.images = images;

    return ipv;
}


/**
 *  设置图片url数组
 */
- (void)setImageUrls:(NSArray *)imageUrls{
    _imageUrls = imageUrls;
    
    //通过sdimage 加载对应地址的图片
    SDWebImageManager *webImageMgr = [[SDWebImageManager alloc] init];
    self.downloadImages = nil;
    for (int i = 0; i < self.imageUrls.count;i++) {
        
        NSString *url = self.imageUrls[i];
        
        [webImageMgr downloadImageWithURL:[NSURL URLWithString:url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
           
            //把加载到的图片存进本地图片数组
            [self.downloadImages addObject:image];
            
            if (i == self.downloadImages.count- 1) {//遍历到最后一个时 赋值给控件
                self.currentImageView.image = self.downloadImages.firstObject;

                self.index = 1;
                //添加定时器
                [self addAETimer];
            }
        }];
    }

}

/**
 *  直接传递图片数组
 */
-(void)setImages:(NSArray *)images{
    _images = images;
    _downloadImages= nil;
    [_downloadImages addObjectsFromArray:images];
}


/**
 *  初始化设置
 */
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
//        self.delegate = self;//设置滑动的代理(UIScrollView)自己为自己的代理
        
        //添加子控件
        UIImageView *currentView = [[UIImageView alloc] init];
        [self addSubview:currentView];
        self.currentImageView = currentView;
        
        UIImageView *willAppearView = [[UIImageView alloc] init];
        [self addSubview:willAppearView];
        self.willAppearImageView = willAppearView;
        
        self.backgroundColor = [UIColor grayColor];
    }
    return self;
}



- (void)layoutSubviews{
    
    //设置内部子控件的frame值
    CGFloat w = self.frame.size.width;
    CGFloat h = self.frame.size.height;
    self.currentImageView.frame = CGRectMake(w, 0, w, h);//默认在scrollView的中间
    self.willAppearImageView.frame = CGRectMake(2 * w, 0, w, h);//默认在右边
    
    //设置最大滚动尺寸
    self.contentSize= CGSizeMake(w * 3, h);
    //隐藏滚动条
    self.showsHorizontalScrollIndicator = NO;
    //设置自动分页
    self.pagingEnabled = YES;
    
    //默认滚动到中间
    self.contentOffset = CGPointMake(w, 0);

}


/**
 *  自动播放掉用
 */
- (void)nextImage{
    
    self.onesAnimate = YES;//防止同一个动画连续掉用两次 yes 表示正在动画
    
    CGFloat w = self.currentImageView.frame.size.width;
    CGFloat h = self.currentImageView.frame.size.height;
    
    //通过动画改变current 和 willAppear 的frame
    //注意 duration 和 delay 的时间和 一定要 和定时器的时间吻合(至少不能大于定时器的掉用时间)
    [UIView animateWithDuration:1.0 delay:1.0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        
        //动画代码
        self.currentImageView.frame = CGRectMake(0, 0, w, h);
        self.willAppearImageView.frame = CGRectMake(w, 0, w, h);
        
    } completion:^(BOOL finished) {
        
        //恢复frame
        if (finished && self.isOnesAnimate) {//同一个动画 这里回来两次，故让第二次进不来
            self.onesAnimate = NO;//动画结束 设置动画状态为no
            
            //掉换指针
            UIImageView *temp = self.currentImageView;//临时保存指针用
            
            self.currentImageView = self.willAppearImageView;
            self.willAppearImageView = temp;
            
            //把将要显示的视图的位置移动到当前视图的右边
            self.willAppearImageView.frame = CGRectMake(2 * w, 0, w, h);
            
            //索引加加
            self.index++;
        }
    }];
    
}


/**
 *  创建定时器
 */
- (void)addAETimer{
//    if (self.timer) {
//        [self removeAETimer];
//    }
//    //这里的掉用时间要和动画时间吻合
//    self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(nextImage) userInfo:nil repeats:YES];
//    //添加到主运行循环
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

}

/**
 *  移除定时器
 */
- (void)removeAETimer
{
    [self.timer invalidate];
    self.timer = nil;
    
}

#pragma mark - 滑动掉用的方法
//开始拖拽,移除定时器
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    [self removeAETimer];
    
}


//正在拖拽,判断方向
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //判断拖拽左右方向
    if (scrollView.contentOffset.x < self.frame.size.width) {
        NSLog(@"向右");
        self.moveDirection = AEImagePlayerViewMoveDirectionRight;
    }else if(scrollView.contentOffset.x > self.frame.size.width){
        NSLog(@"向左移");
        self.moveDirection = AEImagePlayerViewMoveDirectionLeft;
    }
}


/**
 *  滑动结束,添加定时器,改变索引
 */
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"滚动结束");
    self.moveDirection = AEImagePlayerViewMoveDirectionWait;
    scrollView.contentOffset = CGPointMake(0, 0);
    if (self.downloadImages.count) {
        self.currentImageView.image = self.downloadImages[self.index];
    }
}


#pragma mark - 直接传图片数组




@end








